<?php

namespace app\common\controller;

use app\common\model\Actionlog;
use app\common\model\Configs;
use app\common\model\Node;
use app\common\model\Role;
use think\Controller;
use think\Request;
use tree\Tree;

class AdminBase extends Controller
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
//      验证登录
        if (!session('admin')) {
            return $this->redirect('admin/login/login');
        }
//        获取菜单
        if (!cache('menuData')) {
            $this->getMenu();
            $menu = cache('menuData');
        } else {
            $menu = cache('menuData');
        }
        $this->assign('menu', $menu);
//        进行验证
        $this->authMessage();
//        获取网站配置
        $this->getAdminConfig();
    }

    private function getAdminConfig(){
        $configModel = new Configs();
        $configData= $configModel->where('config_name','adminconfig')->field('config_value')->find();
        $this->assign('AdminConfigData',json_decode($configData['config_value'],true));
    }
    /**
     * 进行权限验证
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function authMessage(){
        $authControle = '/'.strtolower(\request()->module()).'/'.strtolower(\request()->controller()).'/'.strtolower(\request()->action());
        $nodeModel = new Node();
        $nodeData = $nodeModel->where('node_name',$authControle)->find();
        if (session('admin.username')!='admin'){
            if ($nodeData!=null){
                if ($nodeData['is_auth']==1){
                    $roleModel = new Role();
                    $nodes = $roleModel->where('role_id',session('admin.role_id'))->field('nodes')->find();
                    $nodeids = explode(',',$nodes['nodes']);
                    if (!in_array($nodeData['node_id'],$nodeids)){
                        return $this->error('权限不足');
                    }else{
                        $this->intActionMessage($nodeData['describe']);
                    }
                }
            }else{
                return $this->error('权限不足');
            }
        }else{
            if ($nodeData!=null){
                $this->intActionMessage($nodeData['describe']);
            }else{
                abort(404);
            }
        }

    }

    /**
     * 操作日志
     * @param $message
     */
    protected function intActionMessage($message){
        $actionLogModel = new Actionlog();
        $data=[
            'action_time'=>time(),
            'admin_id'=>session('admin.admin_id'),
            'action_log'=>$message,
        ];
        $actionLogModel->save($data);
    }

    /**
     * 获取菜单方法
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function getMenu()
    {
        $nodeModel = new Node();
        if (session('admin.username') == 'admin') {
            $data = $nodeModel->where('type', 'NEQ', 3)->order('sort desc')->select();
            $nodeData = collection($data)->toArray();
            $menuData = getTreeData($nodeData, 'pid', 'node_id');
        } else {
            $roleModel = new Role();
            $nodes = $roleModel->where('role_id',session('admin.role_id'))->field('nodes')->find();
            $nodeIds = explode(',',$nodes['nodes']);
            $nodeData = $nodeModel->where('node_id','IN',$nodeIds)->where('type', 'NEQ', 3)->order('sort desc')->select();
            $menuData = getTreeData(collection($nodeData)->toArray(),'pid','node_id');
        }
        cache('menuData',$menuData);
    }

    /**
     * 返回提示信息
     * @param $code
     * @param $message
     * @param string $url
     * @return array
     */
    public function resMessage($code, $message, $url = '')
    {
        if ($url == '') {
            return ['code' => $code, 'message' => $message];
        } else {
            return ['code' => $code, 'message' => $message, 'url' => $url];
        }

    }

    /**
     * 获取所有的子级ID
     * @param $pid
     * @return array
     */
    public function getsonids($pid, $cid)
    {
        $data = $this->getSonData($pid, $cid);
        if ($data != null) {
            $sonids = [];
            foreach ($data as $v) {
                $sonids[] = $v[$cid];
            }
        } else {
            $sonids = null;
        }

        return $sonids;
    }

    /**
     * 获取所有的子级数据
     * @param $pid
     * @return array
     */
    public function getSonData($pid, $cid)
    {
        $data = $this->getNodeData();
        if ($data != null) {
            $tree = new Tree();
            $sondata = $tree::channelList($data, $pid, "&nbsp;", $cid);
        } else {
            $sondata = null;
        }

        return $sondata;
    }

    /**
     * 获取所有的节点数据
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function getNodeData()
    {
        $nodeMode = new Node();
        $data = $nodeMode->select();
        return $data;
    }

    /**
     * 获取所有父节点id
     * @param $id
     * @param $cid
     * @return array|null
     */
    public function getfathrerids($id, $cid)
    {
        $data = $this->getFatherData($id, $cid);
        if ($data != null) {
            $fatherIds = [];
            foreach ($data as $v) {
                $fatherIds[] = $v[$cid];
            }
        } else {
            $fatherIds = null;
        }
        return $fatherIds;
    }

    /**
     * 获取所有父级节点数据
     * @param $id
     * @param $cid
     * @return array|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFatherData($id, $cid)
    {
        $data = $this->getNodeData();
        if ($data != null) {
            $tree = new Tree();
            $parentdata = $tree::parentChannel($data, $id, $cid);
        } else {
            $parentdata = null;
        }
        return $parentdata;

    }

    /**
     * 更新菜单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function upMenu()
    {
        if (\request()->isAjax()) {
            cache('menuData', null);
            if (!cache('menuData')) {
                return $this->resMessage(1, '更新成功');
            } else {
                return $this->resMessage(1, '更新失败');
            }
        } else {
            abort(404);
        }
    }

    /**
     * 图片上传
     * @return array
     */


    public function upload($file,$path){
        if ($file){
            $info = $file->validate(['size'=>1024*1024*5,'ext'=>'ico'])->move($path,'favicon.ico',true);
            if ($info){
                $urls= $_SERVER['SERVER_NAME'];
                return $this->resMessage(0,'上传成功','http://'.$urls.'/'.$info->getSaveName());
            }else{
                return $this->resMessage(1,$file->getError());
            }
        }else{
            return $this->resMessage(1,'请选择文件');
        }
    }

}
